package com.aabte.nettyleran.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/11
 */
public class AsyncTimeServerHandler implements Runnable {

    private String host;

    private int port;

    private CountDownLatch latch;

    private AsynchronousServerSocketChannel assc;

    public AsyncTimeServerHandler(String host, int port) {
        this.host = host;
        this.port = port;

        try {
            assc = AsynchronousServerSocketChannel.open();
            assc.bind(new InetSocketAddress(host, port));
            System.out.println("The time server is start in port: " + port);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);

        doAccept();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doAccept() {
        assc.accept(this, new AcceptCompletionHandler());
    }

    public CountDownLatch getLatch() {
        return latch;
    }

    public AsynchronousServerSocketChannel getAssc() {
        return assc;
    }
}
